package menu_api

import (
	"fmt"
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/res"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func (MenuApi) MenuRemoveView(c *gin.Context) {
	var cr models.RemoveRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		res.FailWithCode(res.ArgumentError, c)
		return
	}

	var menuList []models.MenuModel
	count := global.DB.Find(&menuList, cr.IDList).RowsAffected
	if count > 0 {
		// 事物
		err := global.DB.Transaction(func(tx *gorm.DB) error {
			err := global.DB.Model(&menuList).Association("Banners").Clear()
			if err != nil {
				global.Log.Error(err)
				return err
			}
			err = global.DB.Delete(&menuList).Error
			if err != nil {
				global.Log.Error(err)
				return err
			}
			return nil
		})
		if err != nil {
			global.Log.Error(err)
			res.Fail("删除失败", c)
		}
	}
	res.OkWithMessage(fmt.Sprintf("共删除 %d 条数据", count), c)
}
